<template>
	<view class="content" v-if="goodsInfo!=''">
		<view class="top-edit">
			<view class="postiion-box">
				<image src="../../static/common/goos-back.png" class="goos-back" @tap="goBack"></image>
				<image src="../../static/common/goos-edit.png" class="goos-edit" @tap="userEdit"></image>
				<view class="uni-pop" v-if="rightTopBtn">
					<view class="home" @tap="goHome"><image src="../../static/common/home-tab.png" class="home-tab"/></view>
					<view class="home" @tap="goSearch"><image src="../../static/common/search-tab.png" class="home-tab"/></view>
					<view class="home share" @tap="share"><image src="../../static/common/share-tab.png" class="home-tab"/></view>
				</view>
			</view>
			
		</view>
		<swiper class="good-imgs" indicator-dots="true" autoplay="true" circular="true"
		 v-if="goodsInfo.small_images" >
			<swiper-item 
			v-for="(img,index) in goodsInfo.small_images.string" :key="index"
			@tap="seeImg(goodsInfo.small_images.string,index)"
			>
				<image :src="img" class="goos-img"></image>
			</swiper-item>
		</swiper>
		<swiper class="good-imgs" indicator-dots="true" autoplay="true" circular="true"
		 v-else>
			<swiper-item >
				<image :src="goodsInfo.pict_url" class="goos-img"></image>
			</swiper-item>
		</swiper>
		<!-- 优惠券 -->
		<view class="coupon" v-if="couponInfo.coupon!=0">
			<image class="coupon-bg" src="../../static/common/coupon-bg.png"></image>
			<view class="coupon-detail" @click="getCouponClickUrl">
				<image src="../../static/common/coupon-detail.png" class="coupon-detail-bg"></image>
				<view class="coupon-num">
					<view class="num-top">
						<text class="icon">￥</text><text>{{couponInfo.coupon?couponInfo.coupon:0}}</text>
					</view>
					<view class="receive">立即领取</view>
				</view>
				<view class="coupon-time">
					<view class="start-time">生效时间：{{couponInfo.coupon_start_time}}</view>
					<view class="end-time">截止日期：{{couponInfo.coupon_end_time}}</view>
				</view>
			</view>
		</view>
		<!-- 商品标题 -->
		<view class="goos-title-block">
			<view class="good-title">
				<image src="../../static/common/taobao.png" class="name-icon"></image>
				<text class="good-name2">{{goodsInfo.title}}</text>
			</view>
			<view class="good-coupon">
				<view class="zk_final_price2" v-if="couponInfo.coupon==0">￥{{goodsInfo.zk_final_price}}</view>
				<view class="zk_final_price" v-if="couponInfo.coupon!=0">原价￥{{goodsInfo.zk_final_price}}</view>
				<view class="after-coupon" v-if="couponInfo.coupon!=0">券后价</view>
				<view class="price" v-if="couponInfo.coupon!=0">
					<text class="money-icon">￥</text>
					{{getPrice(couponInfo.zk_final_price,couponInfo.coupon)}}
				</view>
			</view>
			<view class="sale-volume">
				<view>{{goodsInfo.nick}}</view>
				<view>月销{{goodsInfo.volume}}</view>
			</view>
		</view>
		<!-- 推荐词 -->
		<!-- <view class="recommend">
			<image src="../../static/common/recommend-img.png" class="recommend-img"></image>
			<view class="recommend-text">
				击败同类店铺开机后给好几个好几个百分点尴哈哈哈肌肤光滑的肌肤的
				光伏发电个他与郭富城个好吃的
			</view>
		</view> -->
		<!-- 商品详情 -->
		<view class="goods-info" style="margin-top: 0;" v-if="goodsInfo.desc_images && goodsInfo.desc_images.length>0">
			<image src="../../static/common/goos-info.png" class="goos-info" style="margin-top: 0;"></image>
			<view class="goods-desc-list">
				<image mode="widthFix" :src="item"  v-for="(item,k) in goodsInfo.desc_images" :key="k" class="imgs"></image>
			</view>
			
		</view>
		<!-- 好物推荐 -->
		<view class="goods-info" v-if="recommendList.length>0">
			<image src="../../static/common/recommend-title.png" class="goos-info"></image>
			<view class="recommend-list">
				<good v-for="(good,index) in recommendList" :key="index" class="good"
				:goodsInfo="good" @goodsDetail="goodsDetail"
				></good>
			</view>
		</view>
		<!-- 底部按钮 -->
		<view class="bottom-btn">
			<image 
			@tap="collection"
			:src="isCollect?'../../static/common/collection-yet.png':'../../static/common/collection-not.png'" class="collection"></image>
			<view class="btn-block">
				<view class="share-btn" @tap="shareGoods">分享赚 ¥ {{yongjin}}</view>
				<view class="coupon-btn"  @click="getCouponClickUrl(couponInfo.coupon)">{{couponInfo.coupon==0?'暂无优惠券':'领券省 ¥'+ couponInfo.coupon}}  </view>
			</view>
		</view>
		
		<!-- 分享商品 -->
		
	</view>
</template>

<script>
	const plug= uni.requireNativePlugin('UZK-Alibcsdk');
	import good from '../../components/goods/good.vue'
	export default{
		name:"goodDetail",
		components:{
			good
		},
		data(){
			return{
				product_id:"",
				goodsInfo:"",
				coupon:'',
				startTime:"",
				endTime:"",
				recommendList:"",//推荐好物
				coupon_click_url:"",//高佣转链
				yongjin:"", //佣金
				isCollect:false,//商品是否收藏
				collectId:"",//收藏id
				apptoken:"",
				shareText:{},
				couponInfo:"",
				footlist:{},
				isHistory:false,
				rightTopBtn:false,
				qrcode:"",
				userId:""
			}
		},
		onBackPress() {
			//退出页面时缓存浏览记录--需要关闭页面的侧滑回退事件
			const HistoryFoot = uni.getStorageSync("HistoryFoot");
			if(!this.isHistory)
			HistoryFoot.push(this.footlist);
			uni.setStorage({
				key:"HistoryFoot",
				data:HistoryFoot
			})
		},
		onLoad(options) {
			uni.showLoading();
			//获取token
			this.apptoken = uni.getStorageSync('apptoken');
			this.userId = uni.getStorageSync("userId");
			this.product_id = options.id;
			//获取商品详情
			this.getGoodsDetail(options.id);
			this.getDetail(options.id);//该接口返回商品优惠券信息
			//佣金
			this.yongjin = uni.getStorageSync('yongjin');
			//获取分享图片
			//this.sharePic();
		},
		methods:{
			seeImg(arry,index){
				uni.previewImage({
						urls: arry,
						current:index,
						indicator:"number",
						loop:true,
						longPressActions: {
								itemList: ['发送给朋友', '保存图片'],
								success: function(data) {
									//console.log(arry[data.index])
									//console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
									if(data.tapIndex == 0){
										//分享到微信
										uni.share({
										    provider: "weixin",
										    scene: "WXSceneSession",
										    type: 2,
										    imageUrl:arry[data.index],
										    success: function (res) {
										        //_this.sharePic();
										    },
										    fail: function (err) {
										        console.log("fail:" + JSON.stringify(err));
										    }
										});
									}else if(data.tapIndex == 1){
										//保存到本地相册
										uni.saveImageToPhotosAlbum({
												filePath: arry[data.index],
												success: function () {
														uni.showToast({
															title:"保存成功"
														})
												}
										});
									}
								},
								fail: function(err) {
										console.log(err.errMsg);
								}
						}
				});
			},
			userEdit(){
				//右上角按钮
				this.rightTopBtn = !this.rightTopBtn;
			},
			goHome(){
				uni.switchTab({
					url:'../home/home'
				})
			},
			sharePic(){
				//请求分享图片
				const _this = this;
				console.log("请求中。。。")
				uni.request({
					url:this.$API.URL + this.$API.tbk_tk_qrcode,
					data:{apptoken:this.apptoken,goodsId:this.product_id},
					success(res) {
						console.log(res)
						if(res.data.success){
								 _this.qrcode = res.data.msg.data.qrcode;
						}
					}
				})
			},
			share(){
				if(!this.apptoken){
					uni.navigateTo({
						url:'../login/login',
						animationType:'slide-in-bottom',
					})
					return;
				}
				const _this = this;
				uni.showActionSheet({
				    itemList: ['微信', '朋友圈'],
				    success: function (res) {
							//console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
							if(res.tapIndex == 0){
								uni.share({
								    provider: "weixin",
								    scene: "WXSceneSession",
								    type: 2,
								    imageUrl:_this.qrcode,
								    success: function (res) {
								        _this.sharePic();
								    },
								    fail: function (err) {
								        console.log("fail:" + JSON.stringify(err));
								    }
								});
							}else if(res.tapIndex == 1){
								uni.share({
								    provider: "weixin",
								    scene: "WXSenceTimeline",
								    type: 2,
								    imageUrl:_this.qrcode,
								    success: function (res) {
											 _this.sharePic();
								        //console.log("success:" + JSON.stringify(res));
								    },
								    fail: function (err) {
								        console.log("fail:" + JSON.stringify(err));
								    }
								});
							}
						},
				})
			},
			goSearch(){
				uni.navigateTo({
					url:'../search/search'
				})
			},
			getDetail(id){
				//该接口返回商品优惠券信息
				const _this = this;
				uni.request({
					url:this.$API.URL + this.$API.tbk_super_search,
					data:{q:id,apptoken:this.apptoken},
					success(res) {
						console.log(res)
						if(res.data.success){
							if(res.data.msg.data && res.data.msg.code !== 4013){
								_this.couponInfo = res.data.msg.data[0];
								_this.getRecommedList(res.data.msg.data[0].category_name)
							}else{
								uni.showModal({
									title:"温馨提示",
									content:res.data.msg,
									success(res) {
										if(res.confirm){
											_this.goBack();
										}
									}
								})
							}
							
						}
					}
				})
			},
			getPrice(price,coupon_amount){
				//计算券后价
				const num = (Number(price)*1000 - Number(coupon_amount)*1000)/1000;
				this.footlist.coupon_price = num;//商品id
				return num;
			},
			collection(){
				if(!this.apptoken){
					uni.navigateTo({
						url:'../login/login',
						animationType:'slide-in-bottom',
					})
					return;
				}
				//收藏与取消收藏
				const _this = this;
				uni.request({
					url:this.$API.URL + this.$API.Collect,
					data:{
						apptoken:this.apptoken,
						goods_id:this.goodsInfo.item_id,
						goods_name:this.goodsInfo.title,
						goods_image_url:this.goodsInfo.pict_url,
						coupon_price:this.goodsInfo.zk_final_price,
						promotion:this.yongjin
					},
					success(res) {
						console.log(res)
						if(res.data.success){
							uni.showToast({
								title:res.data.msg
							})
							_this.isCollect = !_this.isCollect;
						}else{
							_this.$CommonJS.showToast(res.data.msg);
						}
					}
				})
			},
			getGoodsDetail(id){
				//根据id获取商品详情
				const _this = this;
				uni.request({
					url:this.$API.URL + this.$API.tbk_item_detailinfo,
					data:{id:id,apptoken:this.apptoken},
					success(res) {
						//console.log(res)
					
						if(res.data.success){
							uni.hideLoading();
							//
							_this.goodsInfo = res.data.msg.data;
							_this.isCollect = res.data.msg.isCollect;
							_this.collectId = res.data.msg.collectId;
							//缓存历史记录
							//去重
							uni.getStorageSync("HistoryFoot").forEach(item=>{
								if(item.goods_id==res.data.msg.data.item_id){
									_this.isHistory = true;
								}
							})
							if(!_this.isHistory){
								_this.footlist.goods_name = res.data.msg.data.short_title;//商品短标题
								_this.footlist.goods_image_url = res.data.msg.data.pict_url;//商品图片
								_this.footlist.goods_id = res.data.msg.data.item_id;//商品id
								_this.footlist.promotion = _this.yongjin;//商品佣金
							}
							
							
						}
					}
				})
			},
			getCouponClickUrl(coupon){
				if(!this.apptoken){
					uni.navigateTo({
						url:'../login/login',
						animationType:'slide-in-bottom',
					})
					return;
				}
				if(coupon == 0){
					this.$CommonJS.showToast("该商品暂无优惠");
					return
				}
				//高佣转链
				const _this = this;
				if(this.coupon_click_url){
					//判断是否已经请求过高佣转链，如果已请求，则停止再次请求,直接跳转高佣链接
					//跳转高佣链接
					this.turnCoupon_click_url(this.coupon_click_url)
				}else{
					uni.request({
						url:this.$API.URL + this.$API.tbk_id_privilege,
						data:{id:this.product_id,apptoken:this.apptoken},
						success(res) {
							console.log(res)
							if(res.data.success){
								_this.coupon_click_url = res.data.msg.data.coupon_click_url;
								//跳转高佣链接
								_this.turnCoupon_click_url(res.data.msg.data.coupon_click_url)
								
							}else{
								if(res.data.msg == "请先在app进行淘宝授权"){
									uni.showModal({
										title:"温馨提示",
										content:"您还没有进行淘宝授权，请先去授权吧",
										confirmText:"去授权",
										success(res) {
										// 	if(res.confirm){
										// 		//去淘宝授权
										// 		//#ifdef APP-PLUS
										// 			plus.runtime.openURL("https://oauth.taobao.com/authorize?response_type=code&client_id=28869937&redirect_uri=https://pandayoupin.com/panda.htm&state=1212&view=wap");
										// 		//#endif
										// 		//#ifdef H5
										// 		window.location.href="https://oauth.taobao.com/authorize?response_type=code&client_id=28869937&redirect_uri=https://pandayoupin.com/panda.htm&state=1212&view=wap";
										// 		//#endif
										// 	}else if (res.cancel) {
										// 			console.log('用户点击取消');
										// 	}//初始化
										plug.init(result=>{
										 if(result.status){
											 console.log("初始化成功");
											 //拉起手淘授权
												plug.login(res=>{
													console.log(res)
													if(res.status){

														//登录成功
														_this.OauthInfo =  res.data;
														
														//拉起淘客静默授权
														plug.qdByhide({
															url:"https://oauth.taobao.com/authorize?response_type=code&client_id=28869937&redirect_uri=https://pandayoupin.com/panda.htm&state=1212&view=wap",
															
														},result=> {
															console.log(result)
															uni.request({
																url:_this.$API.URL + _this.$API.getRelation_id,
																data:{
																	code:result.data.code,
																	state:result.data.state,
																	apptoken:_this.apptoken,
																	userId:_this.userId
																},
																success(res) {
																	console.log(res)
																	if(res.data.success){
																		uni.setStorage({
																			key:"isAutoTbao",
																			data:true,
																			success() {
																				uni.showToast({
																					title:"授权成功"
																				})
																			}
																		})
																		
																	}else{
																		uni.showModal({
																			title:"淘宝授权失败",
																			content:res.data.msg
																		})
																	}
																},
																fail(res) {
																	uni.showToast({
																		title:"授权失败"
																	})
																}
															})
														});
													}else{
														_this.$CommonJS.showToast(res.msg)
													}
												});  
										 }else{
											 console.log("初始化失败");
											 _this.$CommonJS.showToast(result.msg)
										 }
										});  
										
										}
									})
								}
							}
							
						}
					})
				}
				
			},
			turnCoupon_click_url(rul){
				//跳转高佣链接
				//#ifdef APP-PLUS
					if (plus.os.name == 'Android') {
						plus.runtime.openURL(rul, function (resp) {
							 
						}, 'com.taobao.taobao');
					}else{
						rul = rul.split('//')[1]
						plus.runtime.openURL('taobao://'+ rul, function (resp) {
							
						}, 'taobao://');
					}
				//#endif
			},
			getRecommedList(goodsName){
				//推荐好物
				const _this = this;
				uni.request({
					url:this.$API.URL + this.$API.tbk_super_search,
					data:{q:goodsName,apptoken:this.apptoken},
					success(res) {
						if(res.data.success){
							const d = res.data.msg.data;
							if(d.length > 0){
								_this.recommendList = d;
							}
							
						}
					}
				})
			},
			goBack(){
				this.$CommonJS.navigateBack()
			},
			goodsDetail(id){
				//商品详情
				this.$CommonJS.navigateTo('../goodDetail/good-detail?id='+id);
			},
			shareGoods(){
				if(!this.apptoken){
					uni.navigateTo({
						url:'../login/login',
						animationType:'slide-in-bottom',
					})
					return;
				}
				//高佣转链
				const _this = this;
				uni.request({
					url:this.$API.URL + this.$API.tbk_id_privilege,
					data:{id:this.product_id,apptoken:this.apptoken},
					success(res) {
						console.log(res)
						if(res.data.success){
							//处理分享文案
							_this.shareText.title = res.data.msg.data.itemInfo.title;//标题
							_this.shareText.zk_final_price = res.data.msg.data.itemInfo.zk_final_price;//原价
							_this.shareText.qh_final_price =  res.data.msg.data.itemInfo.qh_final_price;//券后价
							_this.shareText.coupon_tpwd =  res.data.msg.data.coupon_tpwd;//优惠券码
							_this.shareText.coupon_click_url = res.data.msg.data.coupon_click_url;//优惠券链接
							//console.log(_this.product_id);
							//页面跳转
							uni.setStorage({
								key:"shareText",
								data:_this.shareText,
								success() {
									uni.navigateTo({
										url:'../shareGoods/share-goods?goodsId='+_this.product_id,
										animationType:"slide-in-bottom",
										animationDuration:500
									})
								}
							})
						
						}else{
							if(res.data.msg == "请现在app进行淘宝授权"){
								uni.showModal({
									title:"温馨提示",
									content:"您还没有进行淘宝授权，请先去授权吧",
									confirmText:"去授权",
									success(res) {
										if(res.confirm){
											//去淘宝授权
											//#ifdef APP-PLUS
												plus.runtime.openURL("https://oauth.taobao.com/authorize?response_type=code&client_id=28869937&redirect_uri=https://pandayoupin.com/panda.htm&state=1212&view=wap");
											//#endif
											//#ifdef H5
											window.location.href="https://oauth.taobao.com/authorize?response_type=code&client_id=28869937&redirect_uri=https://pandayoupin.com/panda.htm&state=1212&view=wap";
											//#endif
										}else if (res.cancel) {
												console.log('用户点击取消');
										}
									}
								})
							}
						}
						
					}
				})
				
			}
		}
	}
</script>

<style scoped>
	@import url("good-detail.css");
</style>
